<?php

namespace App\Http\Repository;

use App\PageView;

class PageViewRepository
{

    private $pageView;

    public function __construct(PageView $pageView)
    {
        $this->pageView = $pageView;
    }

    //得到当年每个月的访问量
    public function getPageViewGroupMouth($year = '')
    {
        $times = $this->pageView
            ->lists('created_at')
            ->toArray();

        $year = !empty($year) ? $year : date('Y');

        $mouth = [
            1 => 0,
            2 => 0,
            3 => 0,
            4 => 0,
            5 => 0,
            6 => 0,
            7 => 0,
            8 => 0,
            9 => 0,
            10 => 0,
            11 => 0,
            12 => 0,
        ];
        foreach ($times as $time) {
            $timeArray = explode('-', $time);
            if ($timeArray[0] != $year) {
                continue;
            } else {
                !empty($mouth[(string)(int)$timeArray[1]]) ? $mouth[(string)(int)$timeArray[1]]++ : $mouth[(string)(int)$timeArray[1]] = 1;
            }
        }

        ksort($mouth);
        return $mouth;
    }

    //得到按地区分组的访问次数
    public function getPageViewGroupArea()
    {
        $areaInfo = \App\PageView::select('address', \DB::raw('count(address) as num'))
            ->whereNotNull('address')
            ->groupBy('address')
            ->orderBy('num', 'desc')
            ->get()
            ->take(10)
            ->toArray();

        return $areaInfo;
    }
}